use crate::vc::BASE_SERVICE_URL;
use crate::vc::VcRedist;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::framework::FrameworkInfo;
use anyhow::{Context, Result};
use console::style;
use crate::download::download_file;

/// 执行安装VC Runtime
pub async fn vc_execute(vc: VcRedist) -> Result<()> {
    let (name, include) = VcRedist::get_vc(vc);
    println!("{} 正在启动[{}]安装...", style("ℹ️").blue(),name);

    download_file(&format!("{BASE_SERVICE_URL}/{include}"), name).await?;

    let status = Command::new(name).arg("/q").status()?;
    if !status.success() {
        println!("{} {}安装失败!", style("❌").red(), name);
    }else {
        println!("{} {}安装成功!", style("✅").green(),name);
    }
    // 删除下载的文件
    remove_file(name)?;

    Ok(())
}
/// 执行.Net Framework 4安装
pub async fn net_execute(framework: FrameworkInfo<'_>) -> Result<()> {
    println!("{} 正在[{}]启动安装...", style("ℹ️").blue(),framework.name);

    download_file(&format!("{BASE_SERVICE_URL}/{}", framework.includes), framework.name).await?;

    let status = Command::new(framework.name).arg("/q").status()?;
    if !status.success() {
        println!("{} {}安装失败!", style("❌").red(),framework.name);
    }else {
        println!("{} {}安装成功!", style("✅").green(),framework.name);
    }

    // 删除下载的文件
    remove_file(framework.name)?;
    Ok(())
}

fn remove_file(output_path: &str) -> Result<()> {
    let path = Path::new(output_path);
    if path.exists() {
        fs::remove_file(path)
            .context("❌ 删除文件失败!")?;
        println!("{} 文件[{}]已删除!", style("✅").green(),output_path);
    } else {
        println!("{} 文件[{}]不存在!", style("⚠️").yellow(),output_path);
    }
    Ok(())
}